package service

import (
	"booksmart/book/internal/repository"
	"booksmart/book/internal/service/sms"
	"context"
	"fmt"
	"math/rand/v2"
)

const codePltId = "12345678"

var (
	ErrCodeSentTooMany   = repository.ErrCodeSentTooMany
	ErrCodeVerifyTooMany = repository.ErrCodeVerifyTooMany
)

type CodeService struct {
	repo   *repository.CodeRepository
	smsSvc sms.Service
}

func NewCodeService(repo *repository.CodeRepository, smsSvc sms.Service) *CodeService {
	return &CodeService{repo: repo, smsSvc: smsSvc}
}

func (svc *CodeService) Send(ctx context.Context, biz string, phone string) error {
	code := svc.generateCode()
	err := svc.repo.Store(ctx, biz, phone, code)
	if err != nil {
		return err
	}
	err = svc.smsSvc.Send(ctx, codePltId, []string{code}, phone)
	if err != nil {
		//可以选择重试，不删除redis
	}
	return err
}

func (svc *CodeService) Verify(ctx context.Context, biz string, phone string, code string) (bool, error) {
	return svc.repo.Verify(ctx, biz, phone, code)
}

func (svc *CodeService) generateCode() string {
	num := rand.IntN(1000000)
	return fmt.Sprintf("%06d", num)
}
